package com.example.agriapp.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.agriapp.model.bean.Article;
import com.example.agriapp.R;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class AddProductActivity extends AppCompatActivity {

    private EditText etTitle, etImageUrl, etContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_product);

        etTitle = findViewById(R.id.et_title);
        etImageUrl = findViewById(R.id.et_image_url);
        etContent = findViewById(R.id.et_content);
        
        Button btnSubmit = findViewById(R.id.btn_submit);
        btnSubmit.setOnClickListener(v -> submitProduct());
    }


    private void submitProduct() {
        String title = etTitle.getText().toString().trim();
        String imageUrl = etImageUrl.getText().toString().trim();
        String content = etContent.getText().toString().trim();
        
        if (title.isEmpty()) {
            Toast.makeText(this, "请输入产品标题", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (imageUrl.isEmpty()) {
            imageUrl = "https://example.com/agriculture/default.jpg"; // 默认图片
        }
        
        if (content.isEmpty()) {
            content = "<p>暂无详细内容</p>";
        } else {
            // 将纯文本转换为HTML格式
            content = "<p>" + content.replace("\n", "</p><p>") + "</p>";
        }
        
        // 创建新产品对象
        Article newArticle = new Article(
                String.valueOf(System.currentTimeMillis()), // 使用时间戳作为ID
                title,
                imageUrl,
                content,
                new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date())
        );

        // 返回结果
        Intent resultIntent = new Intent();
        resultIntent.putExtra("newArticle", newArticle);
        setResult(RESULT_OK, resultIntent);
        finish();
    }
}